package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dto.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>implements AdUserService {
/*
* todo 用户登录
*  */
    @Override
    public ResponseResult login(AdUserDTO adUserDTO) {
        //TODO 参数校验
        //todo 1. 检查参数  (用户名 密码不能为空)
        if (adUserDTO==null||StringUtils.isBlank(adUserDTO.getName())||StringUtils.isBlank(adUserDTO.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空!");
        }
        //todo  2. 根据用户名查询用户
        LambdaQueryWrapper<AdUser> lambdaQuery = Wrappers.lambdaQuery();
        LambdaQueryWrapper<AdUser> eq = lambdaQuery.eq(AdUser::getName, adUserDTO.getName());
        AdUser adUser = getOne(eq);
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //todo 3. 校验密码    (用户输入密码+salt)md5
        String password = adUser.getPassword();
        String inputPassword = DigestUtils.md5DigestAsHex((adUserDTO.getPassword() + adUser.getSalt()).getBytes());
        if (!password.equals(inputPassword)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入不正确");
        }
        //todo 4. 检查用户状态   正常:9
        //    Integer a = 10;   Integer b = 10;   a == b   true
        //    Integer c = 288    Integer d = 288   c == d   false
        if (!adUser.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //todo 5. 修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //todo 6. 颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //返回用户信息
        AdUserVO adUserVO = new AdUserVO();
        //将adUser属性copy到adUserVO中
        BeanUtils.copyProperties(adUser, adUserVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
